package com.github.llyb120.driver.qiuya;

import com.github.llyb120.driver.qiuya.request.ReqBase;

import javax.xml.crypto.Data;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import static com.github.llyb120.driver.qiuya.request.ReqBase.COMMAND_DROP_DB;

public class Database {

    public QiuyaClient client;
    private Map<String, Collection> colMap = new HashMap<>();
    private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    private ReentrantReadWriteLock.WriteLock wl;
    private ReentrantReadWriteLock.ReadLock rl;
    String name;

    public Database(QiuyaClient client, String name){
        this.name = name;
        this.client = client;
        this.wl = lock.writeLock();
        this.rl = lock.readLock();
    }

    public Collection getCollection(String colName){
        wl.lock();
        Collection col = colMap.get(colName);
        if (col == null) {
            col = new Collection(this, colName);
            colMap.put(colName, col);
        }
        wl.unlock();
        return col;
    }

    public void drop(){
        client.send(COMMAND_DROP_DB, new ReqBase(name, null));
    }
}
